package edu.gatech.cs2340.tigershroud;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

/**
 * Handles all database administration calls for the User database.
 * @author 
 *
 */
public class UserDataSource 
{
	// Database fields
	private SQLiteDatabase userdb;
	private UserSQLiteHelper dbHelper;
	private String[] allColumns = {
			UserSQLiteHelper.COLUMN_ID,
			UserSQLiteHelper.COLUMN_UNAME, 
			UserSQLiteHelper.COLUMN_PASS, 
			UserSQLiteHelper.COLUMN_NAME, 
			UserSQLiteHelper.COLUMN_EMAIL,
			UserSQLiteHelper.COLUMN_TYPE, 
			UserSQLiteHelper.COLUMN_QUES,
			UserSQLiteHelper.COLUMN_ANSW
			};

	public UserDataSource(Context context) 
	{
		dbHelper = new UserSQLiteHelper(context);
	}

	/**
	 * Gets a database that the app can write to.
	 * @throws SQLException if there is no database to open
	 */
	public void open() throws SQLException 
	{
		userdb = dbHelper.getWritableDatabase();
	}

	/**
	 * Closes the database after use.
	 */
	public void close() 
	{
		dbHelper.close();
	}
	
	/**
	 * Creates a user and puts the necessary info in the database.
	 * @param name The user's username
	 * @param pass The user's password
	 * @return The user object of the newly created user.
	 */
	public User createUser(String uname, String pass, String name, String email, String type, String question, String answer) 
	{
		ContentValues values = new ContentValues();
		values.put(UserSQLiteHelper.COLUMN_UNAME, uname);
		values.put(UserSQLiteHelper.COLUMN_PASS, pass);
		values.put(UserSQLiteHelper.COLUMN_NAME, name);
		values.put(UserSQLiteHelper.COLUMN_EMAIL, email);
		values.put(UserSQLiteHelper.COLUMN_TYPE, type);
		values.put(UserSQLiteHelper.COLUMN_QUES, question);
		values.put(UserSQLiteHelper.COLUMN_ANSW, answer);
	
		long insertId = userdb.insert(UserSQLiteHelper.TABLE_USERS, null, values);
		
		// To show how to query
		Cursor cursor = userdb.query(UserSQLiteHelper.TABLE_USERS,
				allColumns, UserSQLiteHelper.COLUMN_ID + " = " + insertId, null,
				null, null, null);
		
		cursor.moveToFirst();
		User temp = cursorToUser(cursor);
		cursor.close();
		return temp;
	}
	
	/**
	 * Queries the db for a user.
	 * @param name The username of the desired user for which we are searching.
	 * @return The user if found. Otherwise, null.
	 */
	public User findUser(String uname) 
	{
		Cursor cursor = userdb.query(UserSQLiteHelper.TABLE_USERS,
				allColumns, UserSQLiteHelper.COLUMN_UNAME + " = '" + uname + "'", null,
				null, null, null);
		
		if(cursor.moveToFirst())
		{
			return cursorToUser(cursor);	
		}
		
		cursor.close();
		return null;
	}
	
	public List<User> usernameRecovery(String email, String password)
	{
		String temp = "SELECT * FROM users WHERE email = '" + email + "' AND pass = '" + password + "'";
		return createUserList(userdb.rawQuery(temp, null));
	}

	public List<User> createUserList(Cursor cursor)
	{
		List<User> ul = new ArrayList<User>();
		if(cursor.moveToFirst())
		{
			while (!cursor.isAfterLast()) 
			{
				User u = cursorToUser(cursor);
				ul.add(u);
				cursor.moveToNext();
			}
		}
		
		if(ul.isEmpty())
		{
			User nullUser = new User();
			nullUser.setUserName("No such user exists");
			nullUser.setEmail("-1");
			ul.add(nullUser);
		}
		cursor.close();
		return ul;
	}
	
	/**
	 * Removes a user from the database.
	 * @param user The username of the user to be removed.
	 */
	public void deleteUser(User user) 
	{
		long id = user.getId();
		userdb.delete(UserSQLiteHelper.TABLE_USERS, UserSQLiteHelper.COLUMN_ID
				+ " = " + id, null);
	}

	/**
	 * Returns a list object of all the users in the db. Used by admins and for
	 * debugging.
	 * @return The list of all users in the db.
	 */
	public List<User> getAllUser() 
	{
		List<User> users = new ArrayList<User>();
		Cursor cursor = userdb.query(UserSQLiteHelper.TABLE_USERS,
				allColumns, null, null, null, null, null);
		cursor.moveToFirst();
		
		while (!cursor.isAfterLast()) 
		{
			User comment = cursorToUser(cursor);
			users.add(comment);
			cursor.moveToNext();
		}
		
		// Make sure to close the cursor
		cursor.close();
		return users;
	}

	/**
	 * Takes in a cursor and returns a user object containing all necessary
	 * data from the top line of the cursor.
	 * @param cursor A query result for a user
	 * @return A user object containing all necessary data from the top 
	 * line of the cursor.
	 */
	private User cursorToUser(Cursor cursor) 
	{
		User user = new User();
		user.setId(cursor.getLong(0));
		user.setUserName(cursor.getString(1));
		user.setPass(cursor.getString(2));
		user.setName(cursor.getString(3));
		user.setEmail(cursor.getString(4));
		user.setType(cursor.getString(5));
		user.setQuestion(cursor.getString(6));
		user.setAnswer(cursor.getString(7));
		return user;
	}
	
	public String userCount()
	{
		String temp = "SELECT COUNT(_id) FROM users";
		Cursor cursor = userdb.rawQuery(temp, null);
		cursor.moveToFirst();
		String result = cursor.getString(0);
		cursor.close();
		return result;
	}
	
	public void insertSuperUser()
	{
		Log.d("UDS", "user db count: " + userCount());
        if(Integer.parseInt(userCount()) < 1)
        {
        	createUser("user", "pass", "name", "email@email.com", "super", "question", "answer");
        }
	}
	
	/**
	 * This method clears the database
	 */
	public void dbClear()
	{
		dbHelper.onUpgrade(userdb, 1, 1);
	}
}
